package com.dpadnavi.vassist.manager;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

import com.dpadnavi.vassist.utils.LogUtils;

import android.app.Activity;

public class ActivityManager {
	
	/** 管理的activity stack */
	private static Stack<Activity> activityStack = new Stack<Activity>();
	/** 记录所有活动的Activity */
	private static final List<Activity> mActivities = new LinkedList<Activity>();
	
	private static ActivityManager instance;

	private ActivityManager() {}

	/**
	 * 获得activityManager 对象
	 * @return
	 */
	public static ActivityManager getManager() {
		if (instance == null) {
			instance = new ActivityManager();
		}
		return instance;
	}

	/** 
	 * 获得当前栈顶Activity
	 * @return 当前运行的activity
	 */
	public Activity getCurrentActivity() {
		Activity activity = null;
		if (!activityStack.empty())
			activity = activityStack.lastElement();
		return activity;
	}

	/**
	 * 获得当前activity的类名
	 * @return	当前activity名字
	 */
	public String getCurrentActivityName() {
		Activity activity = null;
		if (!activityStack.empty())
			activity = activityStack.lastElement();
		return activity != null ? activity.getClass().getSimpleName() : "";
	}

	/** 将当前Activity推入栈中 */
	public void pushActivity(Activity activity) {
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
		mActivities.add(activity);
	}
	
	/** 退出栈顶Activity */
	public void popActivity(Activity activity) {
		if (activity != null) {
			// 在从自定义集合中取出当前Activity时，也进行了Activity的关闭操作
			activity.finish();
			activityStack.remove(activity);
			activity = null;
			mActivities.remove(activity);
		}
	}

	/** 退出栈中所有Activity */
	public void exitApp(Class<?> cls) {
		while (true) {
			Activity activity = getCurrentActivity();
			LogUtils.i("当前Activity类名："+getCurrentActivityName());
			if (activity == null) {
				break;
			}
			if (activity.getClass().equals(cls)) {
				break;
			}
			popActivity(activity);
		}
	}

	/** 
	 * 获取activity栈大小
	 * @return 压栈数量
	 */
	public int getActiivtyStackSize() {
		if (!activityStack.empty()) {
			return activityStack.size();
		} else {
			return 0;
		}
	}

	/** 关闭所有Activity */
	public static void finishAll() {
		List<Activity> copy;
		synchronized (activityStack) {
			copy = new ArrayList<Activity>(activityStack);
		}
		for (Activity activity : copy) {
			activity.finish();
		}
	}
}
